package com.dxhackday.ppicker;

import com.dxhackday.ppicker.model.PhotoManager;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.fxml.FXMLLoader;
import javafx.scene.Group;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.stage.DirectoryChooser;
import javafx.stage.Stage;

import java.io.File;
import java.io.IOException;

/**
 * @author Sergey Lyadzhin
 * @author Alexandr Vorobiev
 * @since 24.11.12 12:02
 */
public class PhotoPickerApplication extends Application {
    private static PhotoPickerApplication application;

    private final ApplicationContext ctx = ApplicationContext.getInstance();

    public static PhotoPickerApplication getPhotoPicker() {
        return application;
    }

    private Stage primaryStage;

    @Override
    public void init() throws Exception {
        super.init();

        application = this;
        ctx.initialize();
    }

    @Override
    public void start(Stage primaryStage) throws IOException {
        this.primaryStage = primaryStage;

        primaryStage.setTitle("Photo Picker");
        primaryStage.setResizable(true);
        primaryStage.setFullScreen(true);
        primaryStage.setScene(new Scene(new Group(), 640, 480, Color.BLACK));
        primaryStage.show();

        DirectoryChooser chooser = new DirectoryChooser();
        chooser.setTitle("Choose the folder with your photos");
        String defaultInputDir = ctx.getConfig().getInputDir();
        if (defaultInputDir != null) {
            File defaultInputDirFile = new File(defaultInputDir);
            if (defaultInputDirFile.exists())
                chooser.setInitialDirectory(defaultInputDirFile);
        }
        File inputDirFile = chooser.showDialog(primaryStage);
        if (inputDirFile == null) {
            Platform.exit();
            return;
        }

        ctx.getConfig().setInputDir(inputDirFile.getPath());

        ctx.setOutputPath(ctx.getConfig().getGoodDir());
        ctx.getPhotoManager().addPictureList(ApplicationContext.BASE_LIST, PhotoManager.getPictureList(inputDirFile.getPath()));
        ctx.getPhotoManager().setCurrentList(ApplicationContext.BASE_LIST);
        ctx.setPictureDelayMillis(ctx.getConfig().getDelay());

        Parent countdownNode = FXMLLoader.load(PhotoPickerApplication.class.getResource("countdown.fxml"));
        primaryStage.getScene().setRoot(countdownNode);
    }

    @Override
    public void stop() throws Exception {
        ctx.getConfig().save();

        super.stop();
    }

    public Stage getPrimaryStage() {
        return primaryStage;
    }

    public static void main(String[] args) {
        launch(args);
    }
}
